package com.sike.netty.jinjie.bytebuf.api;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.util.internal.StringUtil;

public class ByteBufPrintUtil {
    /**
     * 打印 ByteBuf 的核心属性
     * @param byteBuf
     * @param action
     */
    public static void printByteBuf(ByteBuf byteBuf, String action) {
        System.out.println("============== " + action + " ================");

        System.out.println("capacity = " + byteBuf.capacity());
        System.out.println("maxCapacity = " + byteBuf.maxCapacity());
        System.out.println("readerIndex = " + byteBuf.readerIndex());
        System.out.println("writerIndex = " + byteBuf.writerIndex());
        System.out.println("readableBytes = " + byteBuf.readableBytes());
        System.out.println("writableBytes = " + byteBuf.writableBytes());


        System.out.println();
    }

    /**
     * 获取 ByteBuf 的 StringBuilder
     * @param byteBuf
     * @param action
     * @return
     */
    public static StringBuilder getPrintBuilder(ByteBuf byteBuf,String action) {
        return new StringBuilder("\r\n============== " + action +"================\r\n")
                .append("capacity = ").append(byteBuf.capacity()).append("\r\n")
                .append("maxCapacity = ").append(byteBuf.maxCapacity()).append("\r\n")
                .append("readerIndex = ").append(byteBuf.readerIndex()).append("\r\n")
                .append("writerIndex = ").append(byteBuf.writerIndex()).append("\r\n");
    }

    /**
     * 打印 ByteBuf 的详情
     * @param byteBuf
     * @param action
     */
    public static void printByteBufDetail(ByteBuf byteBuf,String action) {
        StringBuilder stringBuilder = getPrintBuilder(byteBuf,action);
        ByteBufUtil.appendPrettyHexDump(stringBuilder,byteBuf);

        System.out.println(stringBuilder.toString());
    }
}
